<template>
  <view class="register-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <view class="logo-section">
        <image :src="logoSrc" mode="aspectFit"></image>
      </view>
    </view>

    <!-- 注册表单 -->
    <view class="form-section">
      <view class="input-group">
        <input
          type="number"
          v-model="phone"
          placeholder="请输入手机号"
          maxlength="11"
          class="input-item"
        />
      </view>

      <view class="input-group">
        <input
          type="text"
          v-model="username"
          placeholder="请输入用户名"
          class="input-item"
        />
      </view>

      <view class="input-group">
        <input
          type="password"
          v-model="password"
          placeholder="请输入密码"
          class="input-item"
        />
      </view>

      <view class="input-group">
        <input
          type="password"
          v-model="confirmPassword"
          placeholder="确认密码"
          class="input-item"
        />
      </view>

      <button class="register-btn" @click="handleRegister">注册</button>

      <view class="login-link" @click="goToLogin">
        已有账号，去登录
      </view>
    </view>
  </view>
</template>

<script>
import Config from '@/Config.js'

export default {
  data() {
    return {
      phone: '',
      username: '',
      password: '',
      confirmPassword: '',
      logoSrc: require('@/static/imgs/assets/lanqiao-logo.svg'),
    };
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },

    // 验证手机号格式
    validatePhone() {
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!this.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none',
        });
        return false;
      }
      if (!phoneReg.test(this.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none',
        });
        return false;
      }
      return true;
    },

    // 验证用户名
    validateUsername() {
      if (!this.username) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none',
        });
        return false;
      }
      return true;
    },

    // 验证密码
    validatePassword() {
      if (!this.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none',
        });
        return false;
      }
      if (this.password.length < 6) {
        uni.showToast({
          title: '密码长度不能少于6位',
          icon: 'none',
        });
        return false;
      }
      return true;
    },

    // 验证确认密码
    validateConfirmPassword() {
      if (!this.confirmPassword) {
        uni.showToast({
          title: '请确认密码',
          icon: 'none',
        });
        return false;
      }
      if (this.password!== this.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none',
        });
        return false;
      }
      return true;
    },

    // 处理注册
    handleRegister() {
      if (!this.validatePhone() ||!this.validateUsername() ||!this.validatePassword() ||!this.validateConfirmPassword()) {
        return;
      }

      // 显示加载中
      uni.showLoading({
        title: '注册中...',
      });

      // 先检查手机号是否已被注册
      uni.request({
        url: Config.URL + 'users',
        success: (res) => {
          if (res.statusCode === 200) {
            const users = res.data;
            const existingUser = users.find((u) => u.phone === this.phone);

            if (existingUser) {
              uni.hideLoading();
              uni.showToast({
                title: '该手机号已被注册',
                icon: 'none',
              });
              return;
            }

            // 计算新用户的id
            let maxId = 0;
            users.forEach((user) => {
              const userId = parseInt(user.id);
              if (!isNaN(userId) && userId > maxId) {
                maxId = userId;
              }
            });
            const newId = (maxId + 1).toString();

            // 手机号未被注册，继续注册流程
            uni.request({
              url: Config.URL + 'users',
              method: 'POST',
              data: {
                id: newId,
                phone: this.phone,
                username: this.username,
                password: this.password,
                addresses: [],
                order: [],
                follows: []
              },
              header: {
                'content-type': 'application/json',
              },
              success: (addRes) => {
                uni.hideLoading();

                if (addRes.statusCode === 201) {
                  uni.showToast({
                    title: '注册成功',
                    icon:'success',
                    duration: 2000,
                  });

                  // 注册成功后跳转到登录页面
                  setTimeout(() => {
                    uni.navigateTo({
                      url: '/pages/login/login',
                    });
                  }, 2000);
                } else {
                  uni.showToast({
                    title: '注册失败，请稍后再试',
                    icon: 'none',
                  });
                }
              },
             
            });
          } else {
            uni.hideLoading();
            uni.showToast({
              title: '网络错误，请稍后再试',
              icon: 'none',
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({
            title: '网络错误，请稍后再试',
            icon: 'none',
          });
        },
      });
    },

    // 跳转到登录页面
    goToLogin() {
      uni.navigateTo({
        url: '/pages/login/login',
      });
    },
  },
};
</script>

<style lang="scss">
.register-container {
  min-height: 100vh;
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column;
  padding: 80rpx 40rpx;
  box-sizing: border-box;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 60rpx;

  .back-btn {
    position: absolute;
    left: 40rpx;
  }

  .logo-section {
    img {
      width: 200rpx;
      height: auto;
    }
  }
}

.form-section {
  flex: 1;
  display: flex;
  flex-direction: column;

  .input-group {
    margin-bottom: 30rpx;
    border-bottom: 1rpx solid #ccc;
    display: flex;
    align-items: center;

    .input-item {
      flex: 1;
      height: 80rpx;
      font-size: 30rpx;
      padding: 0 10rpx;
      border: none;
      outline: none;
      background-color: transparent;
    }
  }

  .register-btn {
    background-color: #007aff;
    color: #fff;
    height: 80rpx;
    width: 100%;
    line-height: 80rpx;
    border-radius: 8rpx;
    font-size: 32rpx;
    margin-top: 40rpx;
    text-align: center;
    border: none;
    outline: none;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .login-link {
    text-align: center;
    margin-top: 30rpx;
    font-size: 28rpx;
    color: #007aff;
    cursor: pointer;
    transition: color 0.3s ease;

    &:hover {
      color: #0056b3;
    }
  }
}
</style>    